# encoding=utf8

import urllib.request
import urllib.parse
import urllib
from urllib.parse import quote
from setuptools.compat import unicode

import bs4
import bs4.element

import os
import os.path
import re
import sys


def grabContent(url):

    req = urllib.request.Request(url)#,headers=conf.HEADERS)

    html = urllib.request.urlopen(req)

    doc = unicode(html.read(),'utf-8','ignore').encode('UTF-8').decode()

    sou = bs4.BeautifulSoup(doc,"html.parser")

    resurl = sou.find('a',cpos='title')['href']

    detlsReq = urllib.request.Request(resurl)

    detlsHTML = urllib.request.urlopen(detlsReq)

    doc = unicode(detlsHTML.read(),'gbk','ignore').encode('UTF-8').decode()

    sou = bs4.BeautifulSoup(doc,"html.parser")

    resurl = sou.find('div',attrs={'class':'t_mp3_info t_mp3_gc'})

    str = resurl.get_text('\n')

    return str


def start_find(musicName):
    musicName = quote(musicName, safe='/:?=')
    url = "http://so.baobao88.com/cse/search?q=" + musicName + "&click=1&s=7343996824506530380&nsid="
    return grabContent(url)


if __name__ == '__main__':

    INTPUT_PATH =  "/Users/Rdxer/Desktop/北京童谣2好学"
    OUTPUT_PATH =  INTPUT_PATH+"_歌词/"
    if not os.path.exists(OUTPUT_PATH):
        os.mkdir(OUTPUT_PATH, 0o755)

    root,dirs,files = next(os.walk(INTPUT_PATH))

    filesNameList = []

    print(files)

    for file in files:
        filesNameList.append(file[0:-4])

    print(filesNameList)

    txtFileName = "js.txt"
    txtFileName = OUTPUT_PATH+txtFileName
    fo = open(txtFileName, "wb")

    res1 = ""

    for file in filesNameList:

        # musicName = "六字歌"
        res = ""
        # try:
        #     res = start_find(file)
        #     res = "\n".join(filter(lambda x: x, res.split('\n')))
        #
        #
        # except:
        #     print(file)
        #     res = ""
        res1 += ('''


            filename = "%s"

function aaa(musicname) {
	window.document.getElementsByClassName("inp_large")[0].value = musicname+" -『好学』"
	window.open("http://so.baobao88.com/cse/search?q="+musicname+"&click=1&s=7343996824506530380&nsid=", "_blank");
	window.document.getElementById("litpic").value = "/uploads/img1/20170721/59716c1532c87.jpg!300X300.jpg"
	document.getElementsByTagName("select")[0].value = 12

}
aaa(filename)



            ''' % (file))

        # print(res)
    fo.write(res1.encode("utf-8"))
    fo.close()




